<template>
  <div class="archives-container">
    <el-card class="archives-header">
      <template #header>
        <div class="card-header">
          <span>员工档案</span>
          <!-- 移除新增按钮，因为档案应该在员工创建时自动建立 -->
        </div>
      </template>

      <el-form :model="queryForm" class="search-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="员工姓名">
              <el-input v-model="queryForm.name" placeholder="请输入员工姓名" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门">
              <el-select
                v-model="queryForm.department_id"
                placeholder="请选择部门"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dept in departments"
                  :key="dept.id"
                  :label="dept.title"
                  :value="dept.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" @click="handleSearch">
                <el-icon><Search /></el-icon>
                查询
              </el-button>
              <el-button @click="handleReset">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card class="archives-content">
      <el-table :data="tableData" style="width: 100%" height="calc(100vh - 330px)">
        <el-table-column prop="employee_id" label="ID" width="80" />
        <el-table-column prop="employee_name" label="员工姓名" :show-overflow-tooltip="true" />
        <el-table-column prop="department_name" label="部门" :show-overflow-tooltip="true" />
        <el-table-column prop="position_name" label="职位" :show-overflow-tooltip="true" />
        <el-table-column prop="entry_date" label="入职日期" :show-overflow-tooltip="true" />
        <el-table-column prop="education" label="学历" :show-overflow-tooltip="true" />
        <el-table-column prop="work_years" label="工作年限" :show-overflow-tooltip="true" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">查看</el-button>
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <!-- 移除删除按钮，档案不应该被删除 -->
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.limit"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 查看抽屉 -->
    <GlobalDrawer
      v-model="viewDrawerVisible"
      title="查看员工档案"
      size="80%"
      :show-footer-buttons="false"
      @close="handleViewDrawerClose"
    >
      <!-- 普通员工档案详情 -->
      <div v-if="profileType === 'admin'">
        <!-- 基本信息 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="form-section-header">基本信息</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-descriptions :column="1" size="small">
                <el-descriptions-item label="员工姓名">
                  {{ (viewData as EmployeeDetail).name }}
                </el-descriptions-item>
                <el-descriptions-item label="工号">
                  {{ (viewData as EmployeeDetail).job_number }}
                </el-descriptions-item>
                <el-descriptions-item label="性别">
                  {{ (viewData as EmployeeDetail).sex === 1 ? '男' : '女' }}
                </el-descriptions-item>
                <el-descriptions-item label="手机号">
                  {{ (viewData as EmployeeDetail).mobile }}
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
            <el-col :span="12">
              <el-descriptions :column="1" size="small">
                <el-descriptions-item label="邮箱">
                  {{ (viewData as EmployeeDetail).email }}
                </el-descriptions-item>
                <el-descriptions-item label="部门">
                  {{ (viewData as EmployeeDetail).department_name }}
                </el-descriptions-item>
                <el-descriptions-item label="职位">
                  {{ (viewData as EmployeeDetail).position_name }}
                </el-descriptions-item>
                <el-descriptions-item label="入职日期">
                  {{ (viewData as EmployeeDetail).entry_date }}
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>
        </el-card>

        <!-- 教育背景 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="form-section-header">教育背景</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-descriptions :column="1" size="small">
                <el-descriptions-item label="学历">
                  {{ (viewData as EmployeeDetail).education }}
                </el-descriptions-item>
                <el-descriptions-item label="专业">
                  {{ (viewData as EmployeeDetail).speciality }}
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
            <el-col :span="12">
              <el-descriptions :column="1" size="small">
                <el-descriptions-item label="毕业院校">
                  {{ (viewData as EmployeeDetail).graduate_school }}
                </el-descriptions-item>
                <el-descriptions-item label="毕业日期">
                  {{
                    (viewData as EmployeeDetail).graduate_day
                      ? formatDate((viewData as EmployeeDetail).graduate_day)
                      : ''
                  }}
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>
        </el-card>

        <!-- 身份信息 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="form-section-header">身份信息</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-descriptions :column="1" size="small">
                <el-descriptions-item label="身份证号">
                  {{ (viewData as EmployeeDetail).idcard }}
                </el-descriptions-item>
                <el-descriptions-item label="生日">
                  {{
                    (viewData as EmployeeDetail).birthday
                      ? formatDate((viewData as EmployeeDetail).birthday)
                      : ''
                  }}
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
            <el-col :span="12">
              <el-descriptions :column="1" size="small">
                <el-descriptions-item label="籍贯">
                  {{ (viewData as EmployeeDetail).native_place }}
                </el-descriptions-item>
                <el-descriptions-item label="民族">
                  {{ (viewData as EmployeeDetail).nation }}
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>
        </el-card>

        <!-- 联系方式 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="form-section-header">联系方式</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-descriptions :column="1" size="small">
                <el-descriptions-item label="家庭地址">
                  {{ (viewData as EmployeeDetail).home_address }}
                </el-descriptions-item>
                <el-descriptions-item label="紧急联系人">
                  {{ (viewData as EmployeeDetail).contact }}
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
            <el-col :span="12">
              <el-descriptions :column="1" size="small">
                <el-descriptions-item label="现居地址">
                  {{ (viewData as EmployeeDetail).current_address }}
                </el-descriptions-item>
                <el-descriptions-item label="紧急联系电话">
                  {{ (viewData as EmployeeDetail).contact_mobile }}
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>
        </el-card>

        <!-- 其他信息 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="form-section-header">其他信息</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-descriptions :column="1" size="small">
                <el-descriptions-item label="个人简介">
                  {{ (viewData as EmployeeDetail).desc }}
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>
        </el-card>
      </div>

      <!-- 律师档案详情 -->
      <div v-else-if="profileType === 'lawyer'">
        <!-- 基本信息 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="form-section-header">基本信息</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-descriptions :column="1" size="small">
                <el-descriptions-item label="律师姓名">
                  {{ (viewData as LawyerDetail).name }}
                </el-descriptions-item>
                <el-descriptions-item label="手机号">
                  {{ (viewData as LawyerDetail).mobile }}
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
            <el-col :span="12">
              <el-descriptions :column="1" size="small">
                <el-descriptions-item label="邮箱">
                  {{ (viewData as LawyerDetail).email }}
                </el-descriptions-item>
                <el-descriptions-item label="性别">
                  {{ (viewData as LawyerDetail).sex === 1 ? '男' : '女' }}
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>
        </el-card>

        <!-- 执业信息 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="form-section-header">执业信息</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-descriptions :column="1" size="small">
                <el-descriptions-item label="执业证号">
                  {{ (viewData as LawyerDetail).idcard }}
                </el-descriptions-item>
                <el-descriptions-item label="执业律所">
                  {{ (viewData as LawyerDetail).firm_name }}
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
            <el-col :span="12">
              <el-descriptions :column="1" size="small">
                <el-descriptions-item label="律师类型">
                  {{ (viewData as LawyerDetail).type === 0 ? '注册律师' : '合作律师' }}
                </el-descriptions-item>
                <el-descriptions-item label="首次执业日期">
                  {{
                    (viewData as LawyerDetail).entry_time
                      ? formatDate((viewData as LawyerDetail).entry_time)
                      : ''
                  }}
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>
        </el-card>

        <!-- 教育背景 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="form-section-header">教育背景</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-descriptions :column="1" size="small">
                <el-descriptions-item label="毕业院校">
                  {{ (viewData as LawyerDetail).education }}
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
            <el-col :span="12">
              <el-descriptions :column="1" size="small">
                <el-descriptions-item label="获得荣誉">
                  {{ (viewData as LawyerDetail).honor }}
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>
        </el-card>

        <!-- 专业信息 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="form-section-header">专业信息</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-descriptions :column="1" size="small">
                <el-descriptions-item label="擅长领域">
                  {{ (viewData as LawyerDetail).adept }}
                </el-descriptions-item>
                <el-descriptions-item label="律师个人简介">
                  {{ (viewData as LawyerDetail).desc }}
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>
        </el-card>
      </div>
    </GlobalDrawer>

    <!-- 编辑抽屉 -->
    <GlobalDrawer
      v-model="editDrawerVisible"
      :title="profileType === 'lawyer' ? '编辑律师档案' : '编辑员工档案'"
      size="80%"
      @confirm="handleSubmit"
      @close="handleEditDrawerClose"
    >
      <!-- 普通员工档案编辑表单 -->
      <el-form v-if="profileType === 'admin'" ref="formRef" :model="formData" label-width="120px">
        <!-- 基本信息 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="form-section-header">基本信息</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="员工姓名" prop="name">
                <el-input v-model="formData.name" placeholder="请输入员工姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工号" prop="job_number">
                <el-input v-model="formData.job_number" placeholder="请输入工号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="formData.sex">
                  <el-radio :label="1">男</el-radio>
                  <el-radio :label="2">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号" prop="mobile">
                <el-input v-model="formData.mobile" placeholder="请输入手机号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="formData.email" placeholder="请输入邮箱" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部门" prop="did">
                <el-select v-model="formData.did" placeholder="请选择部门" style="width: 100%">
                  <el-option
                    v-for="dept in departmentOptions"
                    :key="dept.id"
                    :label="dept.title"
                    :value="dept.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="职位" prop="position_id">
                <el-select
                  v-model="formData.position_id"
                  placeholder="请选择职位"
                  style="width: 100%"
                >
                  <el-option
                    v-for="position in positionOptions"
                    :key="position.id"
                    :label="position.title"
                    :value="position.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入职日期" prop="entry_time">
                <el-date-picker
                  v-model="formData.entry_time"
                  type="date"
                  placeholder="请选择入职日期"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 教育背景 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="form-section-header">教育背景</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="学历" prop="education">
                <el-select
                  v-model="formData.education"
                  placeholder="请选择学历"
                  style="width: 100%"
                >
                  <el-option label="小学" value="小学" />
                  <el-option label="初中" value="初中" />
                  <el-option label="高中" value="高中" />
                  <el-option label="大专" value="大专" />
                  <el-option label="本科" value="本科" />
                  <el-option label="硕士" value="硕士" />
                  <el-option label="博士" value="博士" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="专业" prop="speciality">
                <el-input v-model="formData.speciality" placeholder="请输入专业" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="毕业院校" prop="graduate_school">
                <el-input v-model="formData.graduate_school" placeholder="请输入毕业院校" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="毕业日期" prop="graduate_day">
                <el-date-picker
                  v-model="formData.graduate_day"
                  type="date"
                  placeholder="请选择毕业日期"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 身份信息 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="form-section-header">身份信息</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="身份证号" prop="idcard">
                <el-input v-model="formData.idcard" placeholder="请输入身份证号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生日" prop="birthday">
                <el-date-picker
                  v-model="formData.birthday"
                  type="date"
                  placeholder="请选择生日"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="籍贯" prop="native_place">
                <el-input v-model="formData.native_place" placeholder="请输入籍贯" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="民族" prop="nation">
                <el-input v-model="formData.nation" placeholder="请输入民族" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 联系方式 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="form-section-header">联系方式</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="家庭地址" prop="home_address">
                <el-input v-model="formData.home_address" placeholder="请输入家庭地址" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="现居地址" prop="current_address">
                <el-input v-model="formData.current_address" placeholder="请输入现居地址" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="紧急联系人" prop="contact">
                <el-input v-model="formData.contact" placeholder="请输入紧急联系人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="紧急联系电话" prop="contact_mobile">
                <el-input v-model="formData.contact_mobile" placeholder="请输入紧急联系电话" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 其他信息 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="form-section-header">其他信息</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="个人简介" prop="desc">
                <el-input
                  v-model="formData.desc"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入个人简介"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form>

      <!-- 律师档案编辑表单 -->
      <el-form
        v-else-if="profileType === 'lawyer'"
        ref="formRef"
        :model="formData"
        label-width="120px"
      >
        <!-- 基本信息 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="form-section-header">基本信息</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="律师姓名" prop="name">
                <el-input v-model="formData.name" placeholder="请输入律师姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号" prop="mobile">
                <el-input v-model="formData.mobile" placeholder="请输入手机号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="formData.email" placeholder="请输入邮箱" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="formData.sex">
                  <el-radio :label="1">男</el-radio>
                  <el-radio :label="2">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 执业信息 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="form-section-header">执业信息</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="执业证号" prop="lawyer_idcard">
                <el-input v-model="formData.lawyer_idcard" placeholder="请输入执业证号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="执业律所" prop="lawyer_firm_name">
                <el-input v-model="formData.lawyer_firm_name" placeholder="请输入执业律所" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="律师类型" prop="lawyer_type">
                <el-select
                  v-model="formData.lawyer_type"
                  placeholder="请选择律师类型"
                  style="width: 100%"
                >
                  <el-option label="注册律师" :value="0" />
                  <el-option label="合作律师" :value="1" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="首次执业日期" prop="lawyer_entry_time">
                <el-date-picker
                  v-model="formData.lawyer_entry_time"
                  type="date"
                  placeholder="请选择首次执业日期"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 教育背景 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="form-section-header">教育背景</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="毕业院校" prop="lawyer_education">
                <el-input v-model="formData.lawyer_education" placeholder="请输入毕业院校" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="获得荣誉" prop="lawyer_honor">
                <el-input v-model="formData.lawyer_honor" placeholder="请输入获得荣誉" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 专业信息 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="form-section-header">专业信息</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="擅长领域" prop="lawyer_adept">
                <el-input v-model="formData.lawyer_adept" placeholder="请输入擅长领域" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="律师个人简介" prop="lawyer_desc">
                <el-input
                  v-model="formData.lawyer_desc"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入律师个人简介"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form>
    </GlobalDrawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Plus, Search, Refresh } from '@element-plus/icons-vue'
  import type { FormInstance } from 'element-plus'
  import { archivesApi } from '@/api/user/archives'
  import { userApi } from '@/api/user'
  import GlobalDrawer from '@/components/common/GlobalDrawer.vue'

  interface Archives {
    employee_id: number
    employee_name: string
    department_name: string
    position_name: string
    entry_date: string
    education: string
    work_years: number
  }

  interface Department {
    id: number
    title: string
  }

  interface Position {
    id: number
    title: string
  }

  // 添加员工档案详情接口
  interface EmployeeDetail {
    id: number
    name: string
    job_number: string
    sex: number
    mobile: string
    email: string
    did: number
    position_id: number
    education: string
    speciality: string
    idcard: string
    birthday: number | string
    native_place: string
    nation: string
    home_address: string
    current_address: string
    contact: string
    contact_mobile: string
    desc: string
    entry_time: number | string
    graduate_school: string
    graduate_day: number | string
    department_name: string
    position_name: string
    entry_date?: string
    // 律师特有字段（但可能为空）
    firm_name?: string
    type?: number
    honor?: string
    adept?: string
    lawyer_entry_time?: number | string
  }

  // 添加律师档案详情接口
  interface LawyerDetail {
    id: number
    name: string
    mobile: string
    email: string
    sex: number
    firm_name: string
    type: number
    idcard: string
    education: string
    honor: string
    adept: string
    desc: string
    entry_time: number | string
    // 员工特有字段（但可能为空）
    job_number?: string
    did?: number
    position_id?: number
    speciality?: string
    birthday?: number | string
    native_place?: string
    nation?: string
    home_address?: string
    current_address?: string
    contact?: string
    contact_mobile?: string
    graduate_school?: string
    graduate_day?: number | string
    department_name?: string
    position_name?: string
    entry_date?: string
  }

  const queryForm = reactive({
    name: '',
    department_id: undefined as number | undefined,
  })

  const tableData = ref<Archives[]>([])
  const departments = ref<Department[]>([])
  const departmentOptions = ref<Department[]>([]) // 部门下拉选项
  const positionOptions = ref<Position[]>([]) // 职位下拉选项

  const pagination = reactive({
    page: 1,
    limit: 10,
    total: 0,
  })

  // 查看抽屉
  const viewDrawerVisible = ref(false)
  const viewData = ref<EmployeeDetail | LawyerDetail>({} as EmployeeDetail | LawyerDetail)
  const profileType = ref<'admin' | 'lawyer'>('admin') // 档案类型：'admin' 或 'lawyer'

  // 编辑抽屉
  const editDrawerVisible = ref(false)
  const submitLoading = ref(false)
  const formRef = ref<FormInstance>()

  // 修改formData的类型定义
  interface FormData {
    id: number | undefined
    employee_id: number | undefined
    // 员工基本信息字段
    name: string
    job_number: string
    sex: number
    mobile: string
    email: string
    did: number | undefined
    position_id: number | undefined
    education: string
    speciality: string
    idcard: string
    birthday: number | Date | string | undefined
    native_place: string
    nation: string
    home_address: string
    current_address: string
    contact: string
    contact_mobile: string
    desc: string
    entry_time: number | Date | string | undefined
    graduate_school: string
    graduate_day: number | Date | string | undefined
    // 律师信息字段
    lawyer_idcard: string
    lawyer_firm_name: string
    lawyer_type: number
    lawyer_education: string
    lawyer_honor: string
    lawyer_adept: string
    lawyer_desc: string
    lawyer_entry_time: number | Date | string | undefined
  }

  const formData = reactive<FormData>({
    id: undefined,
    employee_id: undefined,
    // 员工基本信息字段
    name: '',
    job_number: '',
    sex: 1,
    mobile: '',
    email: '',
    did: undefined,
    position_id: undefined,
    education: '',
    speciality: '',
    idcard: '',
    birthday: undefined,
    native_place: '',
    nation: '',
    home_address: '',
    current_address: '',
    contact: '',
    contact_mobile: '',
    desc: '',
    entry_time: undefined,
    graduate_school: '',
    graduate_day: undefined,
    // 律师信息字段
    lawyer_idcard: '',
    lawyer_firm_name: '',
    lawyer_type: 0,
    lawyer_education: '',
    lawyer_honor: '',
    lawyer_adept: '',
    lawyer_desc: '',
    lawyer_entry_time: undefined,
  })

  // 格式化日期
  const formatDate = (timestamp: any) => {
    if (!timestamp || timestamp === '') return ''
    // 确保是数字类型
    const numTimestamp = typeof timestamp === 'number' ? timestamp : Number(timestamp)
    if (isNaN(numTimestamp) || numTimestamp <= 0) return ''
    // 检查是否为秒级时间戳（小于等于10位数字）
    const timestampMs = String(numTimestamp).length <= 10 ? numTimestamp * 1000 : numTimestamp
    const date = new Date(timestampMs)
    // 检查日期是否有效
    if (isNaN(date.getTime())) return ''
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
  }

  // 格式化日期用于输入控件
  const formatDateForInput = (timestamp: any) => {
    // 处理空值情况
    if (!timestamp || timestamp === '' || timestamp <= 0) return undefined

    // 如果已经是Date对象，直接返回
    if (timestamp instanceof Date) {
      return timestamp
    }

    // 处理字符串日期格式（如果后端返回的是日期字符串）
    if (typeof timestamp === 'string' && timestamp.includes('-')) {
      const date = new Date(timestamp)
      if (!isNaN(date.getTime())) {
        return date
      }
    }

    // 处理数字类型（时间戳）
    const numTimestamp = typeof timestamp === 'number' ? timestamp : Number(timestamp)
    if (isNaN(numTimestamp)) return undefined

    // 检查是否为秒级时间戳（小于等于10位数字）
    const timestampMs = String(numTimestamp).length <= 10 ? numTimestamp * 1000 : numTimestamp
    const date = new Date(timestampMs)

    // 检查日期是否有效且不为1970年
    if (isNaN(date.getTime()) || date.getTime() < 10000000000) return undefined

    return date
  }

  const loadArchivesList = async () => {
    try {
      const params = {
        ...queryForm,
        page: pagination.page,
        limit: pagination.limit,
      }
      const res = await archivesApi.getList(params)
      if (res.code === 0) {
        // 处理数据，确保字段名匹配
        tableData.value = res.data.list.map((item: any) => {
          return {
            employee_id: item.employee_id,
            employee_name: item.employee_name,
            department_name: item.department_name,
            position_name: item.position_name,
            entry_date: item.entry_date
              ? item.entry_date
              : item.entry_time > 0
                ? formatDate(item.entry_time)
                : '',
            education: item.education,
            work_years: item.work_years || 0,
          }
        })
        pagination.total = res.data.total
      }
    } catch (error) {
      console.error('加载档案列表失败:', error)
    }
  }

  const loadDepartments = async () => {
    try {
      // 获取扁平结构的部门列表，用于搜索筛选
      const res = await userApi.getDepartmentOptions({})
      if (res.code === 0) {
        // 生成带缩进的部门列表
        departments.value = generateIndentedDepartments(res.data)
      } else {
        console.warn('获取部门列表失败:', res.msg)
        departments.value = []
      }
    } catch (error) {
      console.error('加载部门列表失败:', error)
      departments.value = []
    }
  }

  // 加载部门下拉选项
  const loadDepartmentOptions = async () => {
    try {
      const res = await userApi.getDepartmentOptions({})
      if (res.code === 0) {
        // 生成带缩进的部门选项列表
        departmentOptions.value = generateIndentedDepartments(res.data)
      } else {
        console.warn('获取部门选项失败:', res.msg)
        departmentOptions.value = []
      }
    } catch (error) {
      console.error('加载部门选项失败:', error)
      departmentOptions.value = []
    }
  }

  // 生成带缩进的部门列表
  const generateIndentedDepartments = (depts: any[]) => {
    // 确保传入的数据是数组
    if (!Array.isArray(depts)) {
      console.warn('部门数据不是数组格式:', depts)
      return [] as Department[]
    }

    const result: Department[] = []

    // 定义部门项的接口
    interface DepartmentItem {
      id: number
      title: string
      pid: number
      sort?: number
    }

    // 递归处理部门树
    const processDepartments = (
      depts: DepartmentItem[],
      parentId: number = 0,
      level: number = 0
    ) => {
      // 先筛选出当前层级的部门，再进行排序
      const currentLevelDepts = depts
        .filter(
          (dept): dept is DepartmentItem =>
            dept &&
            typeof dept === 'object' &&
            typeof dept.pid === 'number' &&
            dept.pid === parentId &&
            typeof dept.id === 'number' &&
            typeof dept.title === 'string'
        )
        .sort((a, b) => (a.sort || 0) - (b.sort || 0) || a.id - b.id)

      currentLevelDepts.forEach(dept => {
        // 添加当前部门（带缩进）
        result.push({
          id: dept.id,
          title: '　'.repeat(level) + dept.title, // 使用全角空格进行缩进
        })

        // 递归处理子部门
        processDepartments(depts, dept.id, level + 1)
      })
    }

    // 处理所有部门，确保即使pid不为0的部门也能显示
    const topLevelDepts = depts
      .filter(
        (dept): dept is DepartmentItem =>
          dept &&
          typeof dept === 'object' &&
          typeof dept.pid === 'number' &&
          dept.pid === 0 &&
          typeof dept.id === 'number' &&
          typeof dept.title === 'string'
      )
      .sort((a, b) => (a.sort || 0) - (b.sort || 0) || a.id - b.id)

    // 先添加顶级部门
    topLevelDepts.forEach(dept => {
      result.push({
        id: dept.id,
        title: dept.title,
      })

      // 递归处理子部门
      processDepartments(depts as DepartmentItem[], dept.id, 1)
    })

    // 添加剩余的非顶级部门（处理可能的孤立部门）
    const remainingDepts = depts.filter(
      (dept): dept is DepartmentItem =>
        dept &&
        typeof dept === 'object' &&
        typeof dept.id === 'number' &&
        typeof dept.title === 'string' &&
        !result.some(item => item.id === dept.id)
    )

    remainingDepts.forEach(dept => {
      result.push({
        id: dept.id,
        title: '　' + dept.title, // 至少添加一个缩进
      })
    })

    return result
  }

  // 加载职位下拉选项
  const loadPositionOptions = async () => {
    try {
      const res = await userApi.getPositionOptions()
      if (res.code === 0) {
        positionOptions.value = res.data
      }
    } catch (error) {
      console.error('加载职位选项失败:', error)
    }
  }

  const handleSearch = () => {
    pagination.page = 1
    loadArchivesList()
  }

  const handleReset = () => {
    queryForm.name = ''
    queryForm.department_id = undefined
    handleSearch()
  }

  const handleEdit = async (row: Archives) => {
    try {
      // 加载下拉选项数据
      await Promise.all([loadDepartmentOptions(), loadPositionOptions()])

      // 获取员工档案详情
      const res = await archivesApi.getDetail(row.employee_id)
      if (res.code === 0) {
        profileType.value = res.profile_type || 'admin'

        // 重置formData以避免旧数据干扰
        Object.keys(formData).forEach(key => {
          const field = key as keyof FormData
          if (typeof formData[field] === 'string') {
            ;(formData[field] as string) = ''
          } else {
            ;(formData[field] as undefined) = undefined
          }
        })

        // 设置基本信息
        formData.id = row.employee_id
        formData.employee_id = row.employee_id

        // 员工基本信息字段
        formData.name = res.data.name || ''
        formData.job_number = res.data.job_number || ''
        formData.sex = res.data.sex || 1
        formData.mobile = res.data.mobile || ''
        formData.email = res.data.email || ''
        formData.did = res.data.did || undefined
        formData.position_id = res.data.position_id || undefined
        formData.education = res.data.education || ''
        formData.speciality = res.data.speciality || ''
        formData.idcard = res.data.idcard || ''

        // 日期字段处理 - 确保即使是0值也能正确处理
        formData.birthday = formatDateForInput(res.data.birthday)
        formData.entry_time = formatDateForInput(res.data.entry_time)
        formData.graduate_day = formatDateForInput(res.data.graduate_day)

        // 其他字段
        formData.native_place = res.data.native_place || ''
        formData.nation = res.data.nation || ''
        formData.home_address = res.data.home_address || ''
        formData.current_address = res.data.current_address || ''
        formData.contact = res.data.contact || ''
        formData.contact_mobile = res.data.contact_mobile || ''
        formData.desc = res.data.desc || ''
        formData.graduate_school = res.data.graduate_school || ''

        // 律师信息字段
        formData.lawyer_idcard = res.data.idcard || '' // 律师的执业证号也存储在idcard字段中
        formData.lawyer_firm_name = res.data.firm_name || ''
        formData.lawyer_type = res.data.type || 0
        formData.lawyer_education = res.data.education || ''
        formData.lawyer_honor = res.data.honor || ''
        formData.lawyer_adept = res.data.adept || ''
        formData.lawyer_desc = res.data.desc || ''
        formData.lawyer_entry_time = formatDateForInput(res.data.lawyer_entry_time)
        editDrawerVisible.value = true
      }
    } catch (error) {
      console.error('获取档案详情失败:', error)
      ElMessage.error('获取档案详情失败')
    }
  }

  const handleView = async (row: Archives) => {
    try {
      // 获取员工档案详情
      const res = await archivesApi.getDetail(row.employee_id)
      if (res.code === 0) {
        profileType.value = res.profile_type || 'admin'

        // 直接使用res.data，避免row和res.data数据冲突
        const formattedData: EmployeeDetail | LawyerDetail = { ...res.data }

        // 根据档案类型处理数据
        if (profileType.value === 'admin') {
          const empData = formattedData as EmployeeDetail
          // 确保entry_date字段正确设置
          if (empData.entry_time) {
            empData.entry_date = formatDate(empData.entry_time)
          } else if (empData.entry_date) {
            // 如果已经有entry_date，确保它是格式化的
            empData.entry_date = formatDate(empData.entry_date)
          }

          // 保留原始的生日和毕业日期，让模板中的formatDate函数来处理格式化
          // 只需要确保字段存在且为数字类型
          if (empData.birthday !== undefined && empData.birthday !== null) {
            empData.birthday = Number(empData.birthday)
          }
          if (empData.graduate_day !== undefined && empData.graduate_day !== null) {
            empData.graduate_day = Number(empData.graduate_day)
          }
        } else {
          // 律师档案
          const lawyerData = formattedData as LawyerDetail
          // 格式化执业日期
          if (lawyerData.entry_time) {
            lawyerData.entry_time = formatDate(lawyerData.entry_time)
          }
        }

        viewData.value = formattedData
        viewDrawerVisible.value = true
      }
    } catch (error) {
      console.error('获取档案详情失败:', error)
      ElMessage.error('获取档案详情失败')
    }
  }

  // 安全的日期转换函数
  const convertToTimestamp = (dateValue: any): number | undefined => {
    if (!dateValue) return undefined

    // 如果已经是数字类型的时间戳，直接处理
    if (typeof dateValue === 'number') {
      // 检查是否已经是秒级时间戳（10位或更少）
      const timestampStr = String(dateValue)
      if (timestampStr.length <= 10) {
        return dateValue // 已经是秒级时间戳
      } else {
        return Math.floor(dateValue / 1000) // 毫秒级转换为秒级
      }
    }

    // 处理Date对象或日期字符串
    const dateObj = new Date(dateValue)

    // 检查日期是否有效且不为1970年
    if (isNaN(dateObj.getTime()) || dateObj.getTime() < 10000000000) {
      return undefined
    }

    return Math.floor(dateObj.getTime() / 1000) // 转换为秒级时间戳
  }

  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()
      submitLoading.value = true

      // 构造提交数据
      const submitData: any = {
        id: formData.id,
      }

      if (profileType.value === 'admin') {
        // 普通员工数据
        Object.assign(submitData, {
          name: formData.name,
          job_number: formData.job_number,
          sex: formData.sex,
          mobile: formData.mobile,
          email: formData.email,
          did: formData.did,
          position_id: formData.position_id,
          education: formData.education,
          speciality: formData.speciality,
          idcard: formData.idcard,
          birthday: convertToTimestamp(formData.birthday),
          native_place: formData.native_place,
          nation: formData.nation,
          home_address: formData.home_address,
          current_address: formData.current_address,
          contact: formData.contact,
          contact_mobile: formData.contact_mobile,
          desc: formData.desc,
          // 转换为秒级时间戳，因为后端使用秒级时间戳
          entry_time: convertToTimestamp(formData.entry_time),
          graduate_school: formData.graduate_school,
          graduate_day: convertToTimestamp(formData.graduate_day),
        })
      } else {
        // 律师数据
        Object.assign(submitData, {
          name: formData.name,
          mobile: formData.mobile,
          email: formData.email,
          sex: formData.sex,
          lawyer_idcard: formData.lawyer_idcard,
          lawyer_firm_name: formData.lawyer_firm_name,
          lawyer_type: formData.lawyer_type,
          lawyer_education: formData.lawyer_education,
          lawyer_honor: formData.lawyer_honor,
          lawyer_adept: formData.lawyer_adept,
          lawyer_desc: formData.lawyer_desc,
          // 转换为秒级时间戳，因为后端使用秒级时间戳
          lawyer_entry_time: convertToTimestamp(formData.lawyer_entry_time),
        })
      }

      // 只能编辑，不能新增
      const res = await archivesApi.edit(submitData)

      if (res.code === 0) {
        ElMessage.success('编辑成功')
        editDrawerVisible.value = false
        loadArchivesList()
      }
    } catch (error) {
      console.error('提交失败:', error)
    } finally {
      submitLoading.value = false
    }
  }

  const handleViewDrawerClose = () => {
    // 查看抽屉关闭时的处理
  }

  const handleEditDrawerClose = () => {
    if (formRef.value) {
      formRef.value.resetFields()
    }
    Object.assign(formData, {
      id: undefined,
      employee_id: undefined,
      // 员工基本信息字段
      name: '',
      job_number: '',
      sex: 1,
      mobile: '',
      email: '',
      did: undefined,
      position_id: undefined,
      education: '',
      speciality: '',
      idcard: '',
      birthday: undefined,
      native_place: '',
      nation: '',
      home_address: '',
      current_address: '',
      contact: '',
      contact_mobile: '',
      desc: '',
      entry_time: undefined,
      graduate_school: '',
      graduate_day: undefined,
      // 律师信息字段
      lawyer_idcard: '',
      lawyer_firm_name: '',
      lawyer_type: 0,
      lawyer_education: '',
      lawyer_honor: '',
      lawyer_adept: '',
      lawyer_desc: '',
      lawyer_entry_time: undefined,
    })
  }

  const handleSizeChange = (val: number) => {
    pagination.limit = val
    loadArchivesList()
  }

  const handleCurrentChange = (val: number) => {
    pagination.page = val
    loadArchivesList()
  }

  onMounted(() => {
    loadArchivesList()
    loadDepartments()
    // 移除 loadEmployees() 调用，因为不再需要员工列表
  })
</script>

<style scoped lang="scss">
  .archives-container {
    padding: 20px;
  }

  .archives-header {
    margin-bottom: 20px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-form {
    margin-top: 20px;
  }

  .archives-content {
    .el-pagination {
      margin-top: 20px;
      justify-content: flex-end;
    }
  }

  .form-section {
    margin-bottom: 20px;

    :deep(.el-card__header) {
      padding: 10px 20px;
      background-color: #f5f7fa;
    }

    .form-section-header {
      font-weight: bold;
      color: #303133;
    }
  }

  // 优化表单布局
  :deep(.el-form-item) {
    margin-bottom: 18px;
  }

  :deep(.el-form-item__label) {
    padding-right: 10px;
  }

  // 优化描述列表布局
  :deep(.el-descriptions__label) {
    width: 120px !important;
  }

  :deep(.el-descriptions__content) {
    word-break: break-all;
  }
</style>
